package com.ylxn.sqlSession;

import com.ylxn.config.BoundSql;
import com.ylxn.pojo.Configuration;
import com.ylxn.pojo.MappedStatement;
import com.ylxn.utils.GenericTokenParser;
import com.ylxn.utils.ParameterMapping;
import com.ylxn.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor{
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) {
        ArrayList<Object> list = null;
        try {
            //1,注册驱动，获取连接
            Connection connection = configuration.getDataSource().getConnection();
            //2,获取sql，例如 select * from user where id = #{id}
            String sql = mappedStatement.getSql();
            //3,转换sql语句,例如 select * from user where id = ?
            BoundSql boundSql = getBoundSql(sql);
            System.out.println(boundSql.getSqlText());
            //4，获取预处理对象
            PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
            //5，设置参数
            List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
            //获取结果全路径
            String resultType = mappedStatement.getResultType();
            Class<?> resultTypeClass = getClassType(resultType);
            //获取参数类全路径
            String paramterType = mappedStatement.getParamterType();
            Class<?> paramterTypeClass = getClassType(paramterType);
            for (int i = 0; i < parameterMappingList.size(); i++) {
                ParameterMapping parameterMapping = parameterMappingList.get(i);
                String content = parameterMapping.getContent();
                //5.1 通过返回获取实体对象中的属性值
                Field field = paramterTypeClass.getDeclaredField(content);
                //5.2 防止私有，设置暴力访问
                field.setAccessible(true);
                Object o = field.get(params[0]);
                preparedStatement.setObject(i+1,o);
            }

            //6，执行sql
            ResultSet resultSet = preparedStatement.executeQuery();
            list = new ArrayList<>();
            //7，封装结果集
            while (resultSet.next()){
                //返回结果对象
                Object obj = resultTypeClass.newInstance();
                //7.1 获取结果元数据
                ResultSetMetaData metaData = resultSet.getMetaData();
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    //获取字段名
                    String columnName = metaData.getColumnName(i);
                    //获取字段值
                    Object value = resultSet.getObject(columnName);
                    // 根据反射或者，根据数据库字段和对象实体之间的关系。完成封装
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    writeMethod.invoke(obj,value);
                }
                list.add(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (List<E>) list;
    }

    @Override
    public int save(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, NoSuchFieldException, IllegalAccessException {
        //1,获取连接
        Connection connection = configuration.getDataSource().getConnection();
        //2,获取sql语句
        String sql = mappedStatement.getSql();
        //3,获取#{}的sql,转换的预处理sql,以及参数指
        BoundSql boundSql = getBoundSql(sql);
        //4,预处理sql
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        List<ParameterMapping> mappingList = boundSql.getParameterMappingList();
        //5，获取结果类
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);
        //6，获取参数类全路径
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramterTypeClass = getClassType(paramterType);
        for (int i = 0; i < mappingList.size(); i++) {
            //7，获取设置的参数列
            ParameterMapping parameterMapping = mappingList.get(i);
            String content = parameterMapping.getContent();
            //8,通过反射获取参数类型
            Field field = paramterTypeClass.getDeclaredField(content);
            //9,避免属性私有，设置暴力访问
            field.setAccessible(true);
            Object o = field.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }
        int i = preparedStatement.executeUpdate();
        return i;
    }

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, NoSuchFieldException, IllegalAccessException {
        //1,获取连接
        Connection connection = configuration.getDataSource().getConnection();
        //2,获取sql语句
        String sql = mappedStatement.getSql();
        //3,获取#{}的sql,转换的预处理sql,以及参数指
        BoundSql boundSql = getBoundSql(sql);
        //4,预处理sql
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        List<ParameterMapping> mappingList = boundSql.getParameterMappingList();
        //5，获取结果类
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);
        //6，获取参数类全路径
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramterTypeClass = getClassType(paramterType);
        for (int i = 0; i < mappingList.size(); i++) {
            //7，获取设置的参数列
            ParameterMapping parameterMapping = mappingList.get(i);
            String content = parameterMapping.getContent();
            //8,通过反射获取参数类型
            Field field = paramterTypeClass.getDeclaredField(content);
            //9,避免属性私有，设置暴力访问
            field.setAccessible(true);
            Object o = field.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }
        int i = preparedStatement.executeUpdate();
        return i;
    }

    @Override
    public int delete(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, NoSuchFieldException, IllegalAccessException {
        //1,获取连接
        Connection connection = configuration.getDataSource().getConnection();
        //2,获取sql语句
        String sql = mappedStatement.getSql();
        //3,获取#{}的sql,转换的预处理sql,以及参数指
        BoundSql boundSql = getBoundSql(sql);
        //4,预处理sql
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        List<ParameterMapping> mappingList = boundSql.getParameterMappingList();
        //5，获取结果类
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);
        //6，获取参数类全路径
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramterTypeClass = getClassType(paramterType);
        for (int i = 0; i < mappingList.size(); i++) {
            //7，获取设置的参数列
            ParameterMapping parameterMapping = mappingList.get(i);
            String content = parameterMapping.getContent();
            //8,通过反射获取参数类型
            Field field = paramterTypeClass.getDeclaredField(content);
            //9,避免属性私有，设置暴力访问
            field.setAccessible(true);
            Object o = field.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }
        int i = preparedStatement.executeUpdate();
        return i;
    }

    private Class<?> getClassType(String paramterType) {
        if (paramterType!=null){
            Class<?> aClass = null;
            try {
                aClass = Class.forName(paramterType);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("参数异常");
            }
            return aClass;
        }
        return null;
    }

    /**
     * 将#{}使用？代替
     * @param sql
     * @return 返回BoundSql
     */
    private BoundSql getBoundSql(String sql) {
        //1,标记处理类：配置标记解析器来完成占位符的解析处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        //4,#{}里解析出来的参数名称
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        //2,标记解析器
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        //3,解析出来的sql
        String parse = genericTokenParser.parse(sql);
        BoundSql boundSql = new BoundSql(parse, parameterMappings);
        return boundSql;
    }
}
